package pt.compflow.interfaces.event;

import java.util.HashMap;
import java.util.Map;

import pt.compflow.Context;
import pt.compflow.flowontology.model.Event;
import pt.compflow.flowontology.model.FlowOntologyModel;
import pt.compflow.interfaces.IOInterfaceBase;
import pt.compflow.interfaces.InterfaceListener;
import pt.compflow.storage.TripleStoreConnection;
import pt.compflow.tools.OntModelHelper;

import com.hp.hpl.jena.rdf.model.Resource;

public abstract class EventInterfaceBase extends IOInterfaceBase implements EventInterface {

	protected Map<String, EventSubscription> subscriptionMap;
	
	protected EventInterfaceBase() {
		subscriptionMap = new HashMap<String, EventSubscription>();
	}

	protected EventInterfaceBase(EventInterfaceBase inputInterface) {
		super(inputInterface);
		subscriptionMap = new HashMap<String, EventSubscription>();
	}
	
	protected String getSubscriptionId(String jobUri, Resource eventClass, Event event) {
		return jobUri + eventClass.getURI() + (event == null ? "" : event.getURI());
	}
	
	@Override
	public String subscribe(Context context, TripleStoreConnection store, OntModelHelper ontModelHelper, FlowOntologyModel jobModel, FlowOntologyModel engineModel,
			String jobUri, Resource eventClass, Event event) {
		String id = getSubscriptionId(jobUri, eventClass, event);
		
		if(!subscriptionMap.containsKey(id)) {
			EventSubscription sub = new EventSubscription(id, jobUri, eventClass.getURI(), event == null ? null : event.getURI());
			subscriptionMap.put(id, sub);
			subscribe(context, store, ontModelHelper, jobModel, engineModel, sub);
		}
		
		return id;
	}
	
	public abstract void subscribe(Context context, TripleStoreConnection store, OntModelHelper ontModelHelper, FlowOntologyModel jobModel, FlowOntologyModel engineModel,
			EventSubscription subscription);
	
	@Override
	public void unsubscribe(Context context, TripleStoreConnection store, OntModelHelper ontModelHelper, FlowOntologyModel jobModel, FlowOntologyModel engineModel,
			String jobUri, Resource eventClass, Event event) {
		String id = getSubscriptionId(jobUri, eventClass, event);
		
		if(subscriptionMap.containsKey(id)) {
			unsubscribe(context, store, ontModelHelper, jobModel, engineModel, subscriptionMap.get(id));
			subscriptionMap.remove(id);
		}
	}
	
	public abstract void unsubscribe(Context context, TripleStoreConnection store, OntModelHelper ontModelHelper, FlowOntologyModel jobModel, FlowOntologyModel engineModel,
			EventSubscription subscription);
		
	@Override
	public void onEvent(String subscriptionId, String jobUri, String eventClassUri, String eventUri) {
		for(InterfaceListener listener : listeners)
			((EventInterfaceListener) listener).onEvent(subscriptionId, jobUri, eventClassUri, eventUri, interfaceUri);
	}

}
